package com.hxbd.test.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.io.FileUtils;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.apache.poi.ss.usermodel.Workbook;

import com.duan.test.utils.Excel.DataHandlers;
import com.duan.test.utils.Excel.DefaultExcelParser;
import com.duan.test.utils.common.JschUtils;


public class MsgSend {

	static List<String> list_7d7e = new ArrayList<String>();
	private static String dsdz_v1 = "dsdz_v1";
	private static String dsdz = "dsdz";
	private static String ctb = "ctb";
	private NioSocketConnector connector;

	public IoSession getIoSession(String add, int port) {
		connector = new NioSocketConnector();
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		connector.getFilterChain().addLast("codec_" + this.toString(),
				new ProtocolCodecFilter(new ByteArrayCodecFactory())); // 设置编码过滤器
		connector.setHandler(new SenderReceiveHandler());// 设置事件处理器
		ConnectFuture cf = connector.connect(new InetSocketAddress(add, port));// 建立连接
		cf.awaitUninterruptibly();// 等待连接创建完成
		return cf.getSession();
	}

	public void close(IoSession session) {
		if (null != session) {
			session.close(true);
			session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
			connector.dispose();
		}
	}

	/**
	 * 发送smart/部标等设备报文 报文中时间用time替代，具体传什么时间和格式通过参数sendtime/timestamp控制
	 * 
	 * @param add
	 *            发送地址
	 * @param port
	 *            端口号
	 * @param msgs
	 *            报文列表
	 * @param sendtime
	 *            发送开始时间
	 * @param internal
	 *            每条报文发送间隔时间
	 * @return
	 */
	public Map<Integer, Date> sendMsg(final String add, final int port,
			final List<String> msgs, String sendtime, final int internal) {
		return sendMsg(add, port, msgs, sendtime, "yy MM dd HH mm ss", internal);
	}

	/**
	 * 发送smart/部标等设备报文 报文中时间用time替代，具体传什么时间和格式通过参数sendtime/timestamp控制
	 * 
	 * @param add
	 *            发送地址
	 * @param port
	 *            端口号
	 * @param msgs
	 *            报文列表
	 * @param sendtime
	 *            发送开始时间
	 * @param timestatmp
	 *            报文时间格式
	 * @param internal
	 *            每条报文发送间隔时间
	 * @return
	 */
	public Map<Integer, Date> sendMsg(final String add, final int port,
			final List<String> msgs, final String sendtime,
			final String timestamp, final int internal) {

		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(timestamp);

		final IoSession session = getIoSession(add, port);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				String timestamp_test = timestamp;
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// Iterator<String> i = l.iterator(); i.hasNext();
				Map<String, String> timemap = new HashMap<String, String>();
				for (int i = 0; i < msgs.size(); i++) {
					long time1 = 0;
					String line = msgs.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String data = null;
					// 便携式冷链
					String send = "";
					if ("7E 07 05".equals(line.substring(0, 8))) {
						timestamp_test = "HH mm ss";
						dateString = new SimpleDateFormat(timestamp_test)
								.format(calender.getTime());
					}
					if ("7E 35".equals(line.substring(0, 5))
							|| "7E 3A".equals(line.substring(0, 5))) {
						String[] datetmp = dateString.split(" ");
						long y = Long.parseLong(datetmp[0]);
						long m = Long.parseLong(datetmp[1]);
						long d = Long.parseLong(datetmp[2]);
						long h = Long.parseLong(datetmp[3]);
						long min = Long.parseLong(datetmp[4]);
						if (min == 26) {
							min = min - 1;
						}// 分，遇到26,置为25
						else if (min == 27) {
							min = min + 1;
						}// 遇到27，置为28
						long s = Long.parseLong(datetmp[5]);
						if (s == 26) {
							s = 28;
							time1 = 2000;
							calender.add(Calendar.SECOND, +2);
						}// 秒:遇到26延迟2秒，遇到27延迟1秒
						else if (s == 27) {
							s = 28;
							time1 = 1000;
							calender.add(Calendar.SECOND, +1);
						}
						String year = String.valueOf(Long.toHexString(y));
						String month = String.valueOf(Long.toHexString(m));
						String day = String.valueOf(Long.toHexString(d));
						String hour = String.valueOf(Long.toHexString(h));
						String minute = String.valueOf(Long.toHexString(min));
						String second = String.valueOf(Long.toHexString(s));
						if (year.length() < 2) {
							year = "0" + year.toUpperCase();
						}
						if (month.length() < 2) {
							month = "0" + month.toUpperCase();
						}
						if (day.length() < 2) {
							day = "0" + day.toUpperCase();
						}
						if (hour.length() < 2) {
							hour = "0" + hour.toUpperCase();
						}
						if (minute.length() < 2) {
							minute = "0" + minute.toUpperCase();
						}
						if (second.length() < 2) {
							second = "0" + second.toUpperCase();
						}
						dateString = year + " " + month + " " + day + " "
								+ hour + " " + minute + " " + second;
						Object[] o = timeReplace(line, calender, dateString,
								timestamp_test, timemap);
						data = o[0].toString();
						calender = (Calendar) o[1];
						byte[] mes = transfer2Bytes(data);
						mes = setMobileNewFlag(mes);// 计算校验码
						System.out.println("发送时间："
								+ format.format(calender.getTime()));
						session.write(mes);// 发送消息
						send = byteToString(mes);
					} else {
						Object[] o = timeReplace(line, calender, dateString,
								timestamp_test, timemap);
						data = o[0].toString();
						calender = (Calendar) o[1];
						byte[] mes = transfer2Bytes(data);
						byte[] message = mes;
//						if (!"7E 09 00".equals(line.substring(0, 8))) {
						setNewFlag(mes);// 计算校验码
						message = edit7d7e(mes);
//						}
						System.out.println("发送时间："
								+ format.format(calender.getTime()));
						session.write(message);// 发送消息
						send = byteToString(message);
					}
					msgtime = calender.getTime();
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000 + time1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (i == msgs.size() - 1) {
						break;
					}
				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		close(session);
		return m;
	}

	/**
	 * 发送字符串报文（二进制转码,小设备使用较多）（只需要获得一次session,便可连续发送）
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param msgs
	 *            报文列表
	 * @param sendtime
	 *            报文发送时间
	 * @param timestatmp
	 *            报文时间格式
	 * @param internal
	 *            时间间隔（单位：s）
	 * @return
	 */
	public Map<Integer, Date> sendString(final String add, final int port,
			final List<String> msgs, final String sendtime,
			final String timestamp, final int internal) {
		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(timestamp);

		final IoSession session = getIoSession(add, port);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Map<String, String> timemap = new HashMap<String, String>();
				for (int i = 0; i < msgs.size(); i++) {
					String line = msgs.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String data;
					// 便携式冷链
					String send = "";
					Object[] o = timeReplace(line, calender, dateString,
							timestamp, timemap);
					data = o[0].toString();
					calender = (Calendar) o[1];
					msgtime = calender.getTime();
					byte[] mes = transfer2Bytes(data);
					System.out.println("发送时间："
							+ format.format(calender.getTime()));
					session.write(mes);// 发送消息
					send = byteToString(mes);
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (i == msgs.size() - 1) {
						break;
					}
				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		close(session);
		return m;
	}

	/**
	 * 发送字符串报文（二进制转码,小设备使用较多，针对于每次发送都要重新获得session类型,报文才能正确解析)
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param msgs
	 *            报文列表
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文时间格式
	 * @param internal
	 *            时间间隔（单位：s）
	 * @return
	 */
	public Map<Integer, Date> sendStringOnAndOff(final String add,
			final int port, final List<String> msgs, final String sendtime,
			final String timestamp, final int internal) {
		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(timestamp);

		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Map<String, String> timemap = new HashMap<String, String>();
				for (int i = 0; i < msgs.size(); i++) {
					NioSocketConnector connector = new NioSocketConnector();
					connector.getFilterChain().addLast("logger",
							new LoggingFilter());
					connector.getFilterChain()
							.addLast(
									"codec",
									new ProtocolCodecFilter(
											new ByteArrayCodecFactory()));
					connector.setHandler(new SenderReceiveHandler());
					ConnectFuture cf = connector.connect(new InetSocketAddress(
							add, port));
					cf.awaitUninterruptibly();
					IoSession session = cf.getSession();
					String line = msgs.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String data;
					// 便携式冷链
					String send = "";
					Object[] o = timeReplace(line, calender, dateString,
							timestamp, timemap);
					data = o[0].toString();
					calender = (Calendar) o[1];
					msgtime = calender.getTime();
					byte[] mes = transfer2Bytes(data);
					System.out.println("发送时间："
							+ format.format(calender.getTime()));
					session.write(mes);// 发送消息
					send = byteToString(mes);
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (null != session) {
						session.close(true);
						session.getCloseFuture().awaitUninterruptibly();// 等待连接断开
						connector.dispose();
					}
					if (i == msgs.size() - 1) {
						break;
					}
				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return m;
	}

	/**
	 * 报文中时间用time替代，具体传什么时间和格式通过参数sendtime/timestamp控制
	 * 
	 * @param add
	 *            发送地址
	 * @param port
	 *            端口号
	 * @param filepath
	 *            报文文件 用相对路径：比如 /Config/test.txt
	 * @param sendtime
	 *            发送开始时间
	 * @param internal
	 *            每条报文发送间隔时间
	 * @return
	 */
	public Map<Integer, Date> sendMsg(final String add, final int port,
			final String filepath, String sendtime, final int internal) {
		List<String> l = new ArrayList<String>();
		try {
			l = FileUtils.readLines(new File(filepath), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendMsg(add, port, l, sendtime, internal);
	}

	/**
	 * 报文中时间用time替代，具体传什么时间和格式通过参数sendtime/timestamp控制
	 * 
	 * @param add
	 *            发送地址
	 * @param port
	 *            端口号
	 * @param filepath
	 *            报文文件 用相对路径：比如 /Config/test.txt
	 * @param sendtime
	 *            发送开始时间
	 * @param internal
	 *            每条报文发送间隔时间
	 * @param startrownum
	 *            从第几行开始发。为0、负数或超过最大条数时默认从开头发
	 * @param count
	 *            发多少条。为0、负数或超过最大条数时默认发送全部
	 * @return
	 */
	public Map<Integer, Date> sendMsg(final String add, final int port,
			final String filepath, final String sendtime, final int internal,
			final int startrownum, final int count) {

		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(
				"yy MM dd HH mm ss");

		final IoSession session = getIoSession(add, port);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				String timestamp_test = "yy MM dd HH mm ss";
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Map<String, String> timemap = new HashMap<String, String>();
				List<String> l = new ArrayList<String>();
				try {
					l = FileUtils.readLines(new File(filepath), "UTF-8");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// TODO Auto-generated method stub
				// Iterator<String> i = l.iterator(); i.hasNext();
				int startnum = 1;
				if (startrownum > 0 && startrownum <= l.size()) {
					startnum = startrownum;
				}
				for (int i = startnum - 1; i < l.size(); i++) {

					long time1 = 0;
					String line = l.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String data;
					// 便携式冷链
					String send = "";
					if ("7E 07 05".equals(line.substring(0, 8))) {
						timestamp_test = "HH mm ss";
						dateString = new SimpleDateFormat(timestamp_test)
								.format(calender.getTime());
					}
					if ("7E 35".equals(line.substring(0, 5))
							|| "7E 3A".equals(line.substring(0, 5))) {
						String[] datetmp = dateString.split(" ");
						long y = Long.parseLong(datetmp[0]);
						long m = Long.parseLong(datetmp[1]);
						long d = Long.parseLong(datetmp[2]);
						long h = Long.parseLong(datetmp[3]);
						long min = Long.parseLong(datetmp[4]);
						if (min == 26) {
							min = min - 1;
						}// 分，遇到26,置为25
						else if (min == 27) {
							min = min + 1;
						}// 遇到27，置为28
						long s = Long.parseLong(datetmp[5]);
						if (s == 26) {
							s = 28;
							time1 = 2000;
							calender.add(Calendar.SECOND, +2);
						}// 秒:遇到26延迟2秒，遇到27延迟1秒
						else if (s == 27) {
							s = 28;
							time1 = 1000;
							calender.add(Calendar.SECOND, +1);
						}
						String year = String.valueOf(Long.toHexString(y));
						String month = String.valueOf(Long.toHexString(m));
						String day = String.valueOf(Long.toHexString(d));
						String hour = String.valueOf(Long.toHexString(h));
						String minute = String.valueOf(Long.toHexString(min));
						String second = String.valueOf(Long.toHexString(s));
						if (year.length() < 2) {
							year = "0" + year.toUpperCase();
						}
						if (month.length() < 2) {
							month = "0" + month.toUpperCase();
						}
						if (day.length() < 2) {
							day = "0" + day.toUpperCase();
						}
						if (hour.length() < 2) {
							hour = "0" + hour.toUpperCase();
						}
						if (minute.length() < 2) {
							minute = "0" + minute.toUpperCase();
						}
						if (second.length() < 2) {
							second = "0" + second.toUpperCase();
						}
						dateString = year + " " + month + " " + day + " "
								+ hour + " " + minute + " " + second;
						Object[] o = timeReplace(line, calender, dateString,
								timestamp_test, timemap);
						data = o[0].toString();
						calender = (Calendar) o[1];
						byte[] mes = transfer2Bytes(data);
						mes = setMobileNewFlag(mes);// 计算校验码
						System.out.println("发送时间："
								+ format.format(calender.getTime()));
						session.write(mes);// 发送消息
						send = byteToString(mes);
					} else {
						Object[] o = timeReplace(line, calender, dateString,
								timestamp_test, timemap);
						data = o[0].toString();
						calender = (Calendar) o[1];
						byte[] mes = transfer2Bytes(data);
						setNewFlag(mes);// 计算校验码
						byte[] message = edit7d7e(mes);
						System.out.println("发送时间："
								+ format.format(calender.getTime()));
						session.write(message);// 发送消息
						send = byteToString(message);
					}
					msgtime = calender.getTime();
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000 + time1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (count <= 0 || count >= l.size() - startnum) {
						if (i == l.size() - 1) {
							break;
						}
					} else {
						if (i == (startnum - 1) + count - 1) {
							break;
						}
					}
				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		close(session);
		return m;
	}

	/**
	 * 发送String（只需要获得一次session,便可连续发送）
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param filepath
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文时间格式
	 * @param internal
	 *            时间间隔（单位：s）
	 * @return
	 */
	public Map<Integer, Date> sendString(final String add, final int port,
			final String filepath, String sendtime, String timestamp,
			final int internal) {
		List<String> l = new ArrayList<String>();
		try {
			l = FileUtils.readLines(new File(filepath), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendString(add, port, l, sendtime, timestamp, internal);
	}

	/**
	 * 发送String（只需要获得一次session,便可连续发送）
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param filepath
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文时间格式
	 * @param internal
	 *            时间间隔（单位：s）
	 * @param startrownum
	 *            从第几行开始发。为0、负数或超过最大条数时默认从开头发
	 * @param count
	 *            发多少条。为0、负数或超过最大条数时默认发送全部
	 * @return
	 */
	public Map<Integer, Date> sendString(final String add, final int port,
			final String filepath, final String sendtime,
			final String timestamp, final int internal, final int startrownum,
			final int count) {
		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(timestamp);

		final IoSession session = getIoSession(add, port);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				Map<String, String> timemap = new HashMap<String, String>();
				List<String> l = new ArrayList<String>();
				try {
					l = FileUtils.readLines(new File(filepath), "UTF-8");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				int startnum = 1;
				if (startrownum > 0 && startrownum <= l.size()) {
					startnum = startrownum;
				}
				for (int i = startnum - 1; i < l.size(); i++) {
					String line = l.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String data;
					// 便携式冷链
					String send = "";
					Object[] o = timeReplace(line, calender, dateString,
							timestamp, timemap);
					data = o[0].toString();
					calender = (Calendar) o[1];
					msgtime = calender.getTime();
					byte[] mes = transfer2Bytes(data);
					System.out.println("发送时间："
							+ format.format(calender.getTime()));
					session.write(mes);// 发送消息
					send = byteToString(mes);
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (count <= 0 || count >= l.size() - startnum) {
						if (i == l.size() - 1) {
							break;
						}
					} else {
						if (i == (startnum - 1) + count - 1) {
							break;
						}
					}

				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		close(session);
		return m;
	}

	/**
	 * 发送String(针对于每次发送都要重新获得session类型,报文才能正确解析)
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param filepath
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文发送时间格式
	 * @param internal
	 *            时间间隔（单位：s）
	 * @return
	 */
	public Map<Integer, Date> sendStringOnAndOff(final String add,
			final int port, final String filepath, String sendtime,
			String timestamp, final int internal) {
		List<String> l = new ArrayList<String>();
		try {
			l = FileUtils.readLines(new File(filepath), "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sendStringOnAndOff(add, port, l, sendtime, timestamp, internal);
	}

	/**
	 * 按excel固定方式发送String设备的报文
	 * 
	 * @param add
	 *            地址
	 * @param port
	 *            端口
	 * @param imei
	 *            imei
	 * @param ecxelfile
	 *            excel文件
	 * @param sendtime
	 *            报文发送时间
	 * @param internal
	 *            时间间隔（单位：s）
	 * @return
	 */
	public Map<Integer, Date> sendStringMsg(final String add, final int port,
			final String imei, final String ecxelfile, String sendtime,
			final int internal) {
		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		final Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(format.parse(sendtime));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		final IoSession session = getIoSession(add, port);
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				List<Object[]> ls = new ArrayList<Object[]>();
				int sheetnum = 0;
				try {
					Workbook wb = DefaultExcelParser.createExcelParser(
							ecxelfile).getWorkBook();
					sheetnum = wb.getNumberOfSheets();
					for (int i = 0; i < sheetnum; i++) {
						List<Object[]> l = Arrays.asList(DataHandlers
								.getInstance(ecxelfile).getData(
										wb.getSheetName(i), 1, -1, 0, -1, true));
						ls.addAll(l);
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				for (int i = 0; i < ls.size(); i++) {
					Object[] line = ls.get(i);
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					double lnt = Double.parseDouble(line[0].toString());
					double lat = Double.parseDouble(line[1].toString());
					double t1 = Double.parseDouble(line[2].toString());
					double t2 = Double.parseDouble(line[3].toString());
					double t3 = Double.parseDouble(line[4].toString());
					double t4 = Double.parseDouble(line[5].toString());
					double speed = Double.parseDouble(line[6].toString());
					String acc = line[7].toString();
					String ack_gthbd2 = "|" + lnt + "|" + lat + "|" + speed
							+ "|" + 80 + "|{acc:" + acc + ",gps:1,t1:" + t1
							+ ",t2:" + t2 + ",t3:" + t3 + ",t4:" + t4 + "}#";
					System.out.println(imei);
					if (!imei.substring(0, 4).equals("3158")
							&& !imei.substring(0, 4).equals("3159")) {
						try {
							throw new Exception("imei必须以3158或3159开头");
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					String ack_gthbd1 = "~" + imei.substring(0, 4)
							+ "&GPSDU&2|" + imei.substring(4, imei.length())
							+ "|";
					System.out.println(ack_gthbd1 + dateString + ack_gthbd2);
					byte[] message = (ack_gthbd1 + dateString + ack_gthbd2)
							.getBytes();
					System.out.println("发送时间："
							+ format.format(calender.getTime()));
					session.write(message);// 发送消息
					String send = byteToString(message);
					System.out.println("发送的报文：" + send);
					calender.add(Calendar.SECOND, +internal);
					m.put(i + 1, msgtime);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if (i == ls.size() - 1) {
						break;
					}

				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");

		close(session);
		return m;
	}

	// //ctbox 7E 09 00
	// private static byte[] setNewFlag(byte[] bs) {
	// //先将7D 01 ,7D 02还原回来
	// bs = senseTran(bs);
	// byte[] da = new byte[bs.length - 15];//ctbox
	// System.arraycopy(bs, 13, da, 0, da.length);//ctbox
	// bs[bs.length - 4] = setNewFlagSub(da);//ctbox
	// int idx = bs.length - 2;
	// bs[idx] = bs[1];
	// for (int j=2;j<idx;j++)
	// bs[idx] ^= bs[j];
	// //将7D,7E转义
	// return sense(bs);
	// }

	private static byte[] setMobileNewFlag(byte[] bs) {
		// 先将7D 01 ,7D 02还原回来
		bs = senseTran(bs);

		int idx = bs.length - 2;
		bs[idx] = bs[0];
		for (int j = 1; j < idx; j++)
			bs[idx] ^= bs[j];

		// 将7D,7E转义
		return sense(bs);
	}

	private static void setNewFlag(byte[] bs) {
		byte[] da = new byte[bs.length - 15];
		System.arraycopy(bs, 13, da, 0, da.length);
		StringBuffer buff = new StringBuffer();
		buff.append(bs[1]);
		buff.append(bs[2]);
		String str = buff.toString();
		// ctbox校验位
		if ("90".equals(str))
			bs[bs.length - 4] = setNewFlagSub(da);
		// 然后gnns校验位
		int idx = bs.length - 2;
		bs[idx] = bs[1];
		for (int j = 2; j < idx; j++)
			bs[idx] ^= bs[j];
	}

	private static byte setNewFlagSub(byte[] da) {
		byte flag = da[1];// 从数据头开始
		for (int i = 2; i < da.length - 2; i++) {
			flag ^= da[i];
		}
		// 校验码
		return flag;
	}

	// public static byte[] transfer2Bytes(String input){
	// String[] arrs = input.split(" ");
	// byte[] bytes = new byte[arrs.length];
	// for (int i = 0; i < arrs.length; i++) {
	// bytes[i] = (byte)Integer.parseInt(arrs[i],16);
	// }
	// return bytes;
	// }

	/**
	 * 格式化指令
	 *
	 * @param input
	 * @return
	 */
	public static byte[] transfer2Bytes(String input) {
		String[] arrs = input.split(" ");
		if (arrs.length < 5) {// 消息指令不足5byte，认定为字符串格式的指令
			return input.getBytes();
		}

		byte[] bytes = new byte[arrs.length];
		for (int i = 0; i < arrs.length; i++) {
			bytes[i] = (byte) Integer.parseInt(arrs[i], 16);
		}
		return bytes;
	}

	public static byte[] edit7d7e(byte[] b) {
		b = subBytes(b, 1, b.length - 2);
		for (int i = 0; i < b.length; i++) {
			if ("125".equals(String.valueOf(b[i]))) {
				String str = String.valueOf(i) + "," + "7d";
				list_7d7e.add(str);
			}
			if ("126".equals(String.valueOf(b[i]))) {
				String str = String.valueOf(i) + "," + "7e";
				list_7d7e.add(str);
			}
		}
		for (int i = 0; i < list_7d7e.size(); i++) {
			String str[] = list_7d7e.get(i).split(",");
			if (str[1].equals("7d")) {
				byte head[] = cutOutByte(b, Integer.valueOf(str[0]));
				int left = (b.length - head.length);
				byte mid[] = { (byte) Integer.parseInt("7d", 16),
						(byte) Integer.parseInt("01", 16) };
				byte tail[] = subBytes(b, Integer.valueOf(str[0]) + 1, left - 1);
				b = getMergeBytes(head, mid);
				b = getMergeBytes(b, tail);
				if (i == list_7d7e.size() - 1)
					break;
				for (int j = (i + 1); j < list_7d7e.size(); j++) {
					String next_str[] = list_7d7e.get(j).split(",");
					int new_index = Integer.valueOf(next_str[0]) + 1;
					list_7d7e.set(j, new_index + "," + next_str[1]);
				}

			}
			if (str[1].equals("7e")) {
				byte head[] = cutOutByte(b, Integer.valueOf(str[0]));
				int left = (b.length - head.length);
				byte mid[] = { (byte) Integer.parseInt("7d", 16),
						(byte) Integer.parseInt("02", 16) };
				byte tail[] = subBytes(b, Integer.valueOf(str[0]) + 1, left - 1);
				b = getMergeBytes(head, mid);
				b = getMergeBytes(b, tail);
				if (i == list_7d7e.size() - 1)
					break;
				for (int j = (i + 1); j < list_7d7e.size(); j++) {
					String next_str[] = list_7d7e.get(j).split(",");
					int new_index = Integer.valueOf(next_str[0]) + 1;
					list_7d7e.set(j, new_index + "," + next_str[1]);
				}
			}
		}
		byte tmp[] = { (byte) Integer.parseInt("7e", 16) };
		b = getMergeBytes(tmp, b);
		b = getMergeBytes(b, tmp);
		list_7d7e.clear();
		return b;
	}

	public static byte[] subBytes(byte[] src, int begin, int count) {
		byte[] bs = new byte[count];
		for (int i = begin; i < begin + count; i++)
			bs[i - begin] = src[i];
		return bs;
	}

	/**
	 * 截取byte数据
	 * 
	 * @param b
	 *            是byte数组
	 * @param j
	 *            是大小
	 * @return
	 */
	public static byte[] cutOutByte(byte[] b, int j) {
		if (b.length == 0 || j == 0) {
			return null;
		}
		byte[] bjq = new byte[j];
		for (int i = 0; i < j; i++) {
			bjq[i] = b[i];
		}
		return bjq;
	}

	/**
	 * 合并两个byte数组
	 * 
	 * @param pByteA
	 * @param pByteB
	 * @return
	 */
	public static byte[] getMergeBytes(byte[] pByteA, byte[] pByteB) {
		int aCount = pByteA.length;
		int bCount = pByteB.length;
		byte[] b = new byte[aCount + bCount];
		for (int i = 0; i < aCount; i++) {
			b[i] = pByteA[i];
		}
		for (int i = 0; i < bCount; i++) {
			b[aCount + i] = pByteB[i];
		}
		return b;
	}

	public static String byteToString(byte[] b) {
		char[] chArr = Hex.encodeHex(b);
		String str = "";
		for (char c : chArr) {
			str += String.valueOf(c).toUpperCase();
		}
		String respone = "";
		for (int i = 0; i < str.length(); i++) {
			if (i % 2 == 0) {
				String tmp = str.substring(i, i + 2);
				respone = respone + " " + tmp;
			}
		}
		respone = respone.substring(1, respone.length());
		return respone;
	}

	private static byte[] senseTran(byte[] bs) {
		IoBuffer buffer = IoBuffer.allocate(256).setAutoExpand(true);
		for (int i = 0; i < bs.length; i++) {
			if (bs[i] == 0x7D) {
				i++;
				if (bs[i] == 0x01)
					buffer.put((byte) 0x7D);
				else if (bs[i] == 0x02) {
					buffer.put((byte) 0x7E);
				} else if (bs[i] == 0x03) {
					buffer.put((byte) 0x1A);
				} else {
					buffer.put((byte) 0x1B);
				}
			} else
				buffer.put(bs[i]);
		}
		buffer.flip();
		bs = new byte[buffer.limit()];
		buffer.get(bs);
		return bs;
	}

	private static byte[] sense(byte[] bs) {
		int count = 0;
		for (int i = 1; i < bs.length - 1; i++) {
			if (bs[i] == 0x7e || bs[i] == 0x7d) {
				count++;
			}
		}

		if (count == 0)
			return bs;

		byte[] by = new byte[bs.length + count];
		count = 0;
		by[count++] = bs[0];
		for (int i = 1; i < bs.length - 1; i++) {
			if (bs[i] == 0x7e) {
				by[count++] = 0x7d;
				by[count++] = 0x02;
			} else if (bs[i] == 0x7d) {
				by[count++] = 0x7d;
				by[count++] = 0x01;
			} else if (bs[i] == 0x1A) {
				by[count++] = 0x7d;
				by[count++] = 0x03;
			} else if (bs[i] == 0x1B) {
				by[count++] = 0x7d;
				by[count++] = 0x04;
			} else {
				by[count++] = bs[i];
			}
		}
		by[count++] = bs[bs.length - 1];
		return by;
	}

	public static String timeToHex(String[] time) {
		String str = "";
		for (int i = 0; i < time.length; i++) {
			String s = Integer.toHexString(Integer.parseInt(time[i]));
			if (s.length() < 2) {
				s = "0" + s;
			}
			if (i == 0) {
				str += s;
			} else {
				str += " " + s;
			}
		}
		return str;
	}

	/**
	 * 发送UDP报文
	 * 
	 * @param add
	 *            发送地址
	 * @param port
	 *            端口
	 * @param msglist
	 *            发送消息列表
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文时间格式
	 * @param internal
	 *            发送时间间隔（S）
	 * @return 每条报文发送时间的MAP
	 * @throws SocketException
	 */
	public Map<Integer, Date> sendUDP(final String add, final int port,
			final List<String> msglist, final String sendtime,
			final String timestamp, final int internal) throws SocketException {
		final Map<Integer, Date> m = new HashMap<Integer, Date>();
		final SimpleDateFormat format = new SimpleDateFormat(timestamp);

		final DatagramSocket ds = new DatagramSocket(
				JschUtils.getLocleNotUsingPort()); // 建立套间字udpsocket服务
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				Calendar calender = Calendar.getInstance();
				try {
					calender.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				// TODO Auto-generated method stub
				Map<String, String> timemap = new HashMap<String, String>();
				for (int i = 0; i < msglist.size(); i++) {
					byte[] buf = null;
					String msg = msglist.get(i);
					String dateString = format.format(calender.getTime());
					Object[] o = timeReplace(msg, calender, dateString,
							timestamp, timemap);
					msg = o[0].toString();
					calender = (Calendar) o[1];
					Date msgtime = calender.getTime();
					try {
						buf = msg.getBytes("UTF-8");
					} catch (UnsupportedEncodingException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} // 数据
					InetAddress destination = null;
					try {
						destination = InetAddress.getByName(add); // 需要发送的地址
						DatagramPacket dp = new DatagramPacket(buf, buf.length,
								destination, port);
						System.out.println("发送时间："
								+ format.format(calender.getTime()));
						ds.send(dp); // 发送数据
						System.out.println("发送的报文：" + byteToString(buf));
						calender.add(Calendar.SECOND, +internal);
						m.put(i + 1, msgtime);
						try {
							Thread.sleep(internal * 1000);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} catch (UnknownHostException e) {
						System.out.println("Cannot open findhost!");
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		t.start();
		try {
			t.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("报文发送完毕，等待连接关闭...");
		ds.close();
		return m;
	}

	/**
	 * 发送mqtt报文
	 * 
	 * @param url
	 * @param topic
	 * @param datalist
	 *            待发送数据列表
	 * @param imei
	 * @param model
	 *            0:便携式 1：固定式
	 * @param sendtime
	 *            报文发送时间
	 * @param timestamp
	 *            报文时间格式
	 * @param internal
	 *            间隔时间，单位:s
	 * @return
	 * @throws IOException
	 *//*
	public  Map<Integer, Date> sendMqttMsg(String url, String topic,
			List<String> datalist, String imei, String model, String sendtime,
			String timestamp, int internal) throws IOException {
		Map<Integer, Date> m = new HashMap<Integer, Date>();
		int code = Integer.parseInt(imei.substring(0, 4));
		String deviceno = imei.substring(4, imei.length());
		int index = 1;
		int qos = 1;
		MemoryPersistence persistence = new MemoryPersistence();
		SimpleDateFormat format = new SimpleDateFormat(timestamp);
		Calendar calender = Calendar.getInstance();
		try {
			calender.setTime(format.parse(sendtime));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			MqttAsyncClient sampleClient = new MqttAsyncClient(url,
					MqttAsyncClient.generateClientId(), persistence);
			MqttConnectOptions connOpts = new MqttConnectOptions();
			connOpts.setCleanSession(false);
			connOpts.setConnectionTimeout(30);;
			System.out.println("Connecting to broker: " + url);
			sampleClient.connect(connOpts);
			if (model.equals(ctb.trim())) {
				System.out.println("固定式冷链--：");
				Gpsmsg2 loc = new Gpsmsg2();
				int count = 1;
				for (int i = 0; i < datalist.size(); i++) {
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String line = datalist.get(i);
					System.out.print("第" + count + "条MQTT_ctb: ");
					String[] aa = line.split("/");
					loc.setType(1); // 0:便携式,1:固定式
					loc.setCmd("gpsmsg"); // 命令码
					loc.setCode(code); // 厂商编码
					loc.setMode(2); // 模式: 1/车牌号 2/设备号或sim卡号
					loc.setDeviceno(deviceno); // 设备号或sim卡号
					loc.setTime(dateString); // 定位时间
					loc.setLat(Double.parseDouble(aa[8])); // 纬度
					loc.setLng(Double.parseDouble(aa[9])); // 经度
					loc.setSpeed(20); // 速度
					loc.setCourse(20); // 方向
					loc.getGpsStatus2().setGps(Integer.parseInt(aa[0])); // status
																			// gps
																			// 只有1才会入库
																			// !请注意!
					loc.getGpsStatus2().setAcc(Integer.parseInt(aa[1])); // status
																			// acc
					loc.getGpsStatus2().setCompress(Integer.parseInt(aa[2])); // status
																				// compress
					loc.getGpsStatus2().setDoor(Integer.parseInt(aa[3])); // status
																			// door
					loc.getTemperature2().setT1(Double.parseDouble(aa[4])); // 温度
					loc.getTemperature2().setT2(Double.parseDouble(aa[5]));
					loc.getTemperature2().setT3(Double.parseDouble(aa[6]));
					loc.getTemperature2().setT4(Double.parseDouble(aa[7]));
					loc.getTemperature2().setH1(10.55);
					// loc.getTemperature2().setH2(Double.parseDouble(aa[9]));
					// loc.getTemperature2().setH3(Double.parseDouble(aa[10]));
					// loc.getTemperature2().setH4(Double.parseDouble(aa[11]));
					System.out.println(loc);
					count++;
					System.out.println(loc);
					List<Gpsmsg2> gpsmsgList = new ArrayList<Gpsmsg2>();
					gpsmsgList.add(loc);
					GpsmsgList2 gl = new GpsmsgList2();
					gl.setGpsmsgList(gpsmsgList);
					MessagePack msgpack = new MessagePack();
					byte[] raw = null;
					raw = ZipUtils.gzip(msgpack.write(gl));
					MqttMessage message = new MqttMessage(raw);
					message.setQos(qos);
					sampleClient.publish(topic, message);
					m.put(index, msgtime);
					index++;
					calender.add(Calendar.SECOND, +internal);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						System.out.println(e);
					}
				}
			} else if (model.equals(dsdz.trim())) {
				System.out.println("便携定式冷链--：");
				Gpsmsg2 loc = new Gpsmsg2();
				int count = 1;
				for (int i = 0; i < datalist.size(); i++) {
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String line = datalist.get(i);
					System.out.print("第" + count + "条MQTT_dsdz: ");
					String[] aa = line.split("/");
					loc.setType(0); // 0:便携式,1:固定式
					loc.setCmd("gpsmsg"); // 命令码
					loc.setCode(code); // 厂商编码
					loc.setMode(2); // 模式: 1/车牌号 2/设备号或sim卡号
					loc.setDeviceno(deviceno); // 设备号或sim卡号
					loc.setTime(dateString); // 定位时间
					loc.setLat(Double.parseDouble(aa[0])); // 纬度
					loc.setLng(Double.parseDouble(aa[1])); // 经度
					loc.setSpeed(20); // 速度
					loc.setCourse(20); // 方向
					loc.getGpsStatus2().setGps(Integer.parseInt(aa[2])); // status
																			// gps
																			// 只有1才会入库
																			// !请注意!
					loc.getGpsStatus2().setBp(Integer.parseInt(aa[3])); // 电量
					loc.getTemperature2().setT1(Double.parseDouble(aa[4])); // 温度
					loc.getTemperature2().setH1(Double.parseDouble(aa[5])); // 湿度
					System.out.println(loc);
					count++;
					List<Gpsmsg2> gpsmsgList = new ArrayList<Gpsmsg2>();
					gpsmsgList.add(loc);
					GpsmsgList2 gl = new GpsmsgList2();
					gl.setGpsmsgList(gpsmsgList);
					MessagePack msgpack = new MessagePack();
					byte[] raw = null;
					raw = ZipUtils.gzip(msgpack.write(gl));
					MqttMessage message = new MqttMessage(raw);
					message.setQos(qos);
					sampleClient.publish(topic, message);
					m.put(index, msgtime);
					index++;
					calender.add(Calendar.SECOND, +internal);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						System.out.println(e);
					}
				}
			} else if (model.equals(dsdz_v1.trim())) {
				long t1 = System.currentTimeMillis();
				long pubSum = 0;
				// System.out.println("Connected,t1:" + t1);
				int count = 1;
				for (int i = 0; i < datalist.size(); i++) {
					String dateString = format.format(calender.getTime());
					Date msgtime = calender.getTime();
					String line = datalist.get(i);
					String[] aa = line.split("/");
					System.out.println("便携定式冷链--：");
					System.out.print("第" + count + "条MQTT_dsdz_v1: ");
					Gpsmsg loc = new Gpsmsg();
					loc.setCmd("gpsmsg");
					loc.setCode(code);
					loc.setMode(2);
					loc.setDeviceno(deviceno);
					loc.setTime(dateString);
					loc.setLat(Double.parseDouble(aa[0]));
					loc.setLng(Double.parseDouble(aa[1]));
					loc.getGpsStatus().setGps(1);
					loc.getGpsStatus().setAcc(0);
					loc.setSpeed(0);
					loc.getGpsStatus().setBp(Integer.parseInt(aa[3]));
					loc.getTemperature().setT1(Double.parseDouble(aa[4]));
					loc.getTemperature().setHumi(Double.parseDouble(aa[5]));
					System.out.println(loc);
					List<Gpsmsg> gpsmsgList = new ArrayList<Gpsmsg>();
					gpsmsgList.add(loc);
					GpsmsgList gl = new GpsmsgList();
					gl.setGpsmsgList(gpsmsgList);

					MessagePack msgpack = new MessagePack();
					byte[] raw = null;
					raw = ZipUtils.gzip(msgpack.write(gl));
					MqttMessage message = new MqttMessage(raw);
					message.setQos(qos);
					long t2 = System.currentTimeMillis();
					sampleClient.publish(topic, message);
					m.put(index, msgtime);
					index++;
					pubSum += System.currentTimeMillis() - t2;
					count++;
					// if (count == 121) {
					// calender.add(Calendar.SECOND, 210);
					// try {
					// Thread.sleep(210*1000);
					// } catch (InterruptedException e) {
					// e.printStackTrace();
					// }
					// }
					// else {
					calender.add(Calendar.SECOND, +internal);
					try {
						Thread.sleep(internal * 1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					// }
				}
				long sum = System.currentTimeMillis() - t1;
				System.out.println("Message published,pubSum:" + pubSum
						+ ",total sum:" + sum);
			}
			sampleClient.disconnect();
			System.out.println("Disconnected");
		} catch (MqttException me) {
			System.out.println("reason " + me.getReasonCode());
			System.out.println("msg " + me.getMessage());
			System.out.println("loc " + me.getLocalizedMessage());
			System.out.println("cause " + me.getCause());
			System.out.println("excep " + me);
			me.printStackTrace();
		}
		return m;
	}*/

	/**
	 * 替换报文时间公共方法 先替换time为dateString，然后传递类型为<t*>的参数值
	 * 
	 * @param line
	 *            待替换的报文
	 * @param dateString
	 *            要替换的时间
	 * @param timestamp
	 *            要替换的时间格式
	 * @return 替换后的报文
	 */
	private static Object[] timeReplace(String line, Calendar c,
			String dateString, String timestamp, Map<String, String> timemap) {
		SimpleDateFormat format = new SimpleDateFormat(timestamp);
		String data = line;
		Pattern pattern1 = Pattern.compile("time([\\+-]\\d+[DdHhMmSs])?");
		Matcher matcher1 = pattern1.matcher(data);
		while (matcher1.find()) {
			String tmpstr = matcher1.group();
			if (tmpstr.contains("+") || tmpstr.contains("-")) {
				String addtime = tmpstr.replaceFirst(tmpstr.split("[\\+-]")[0],
						"").replaceAll("\\+", "");
				if (tmpstr.contains("+")) {
					tmpstr = tmpstr.replaceAll("\\+", "\\\\\\+");
				}
				if (addtime.endsWith("d") || addtime.endsWith("D")) {
					c.add(Calendar.DAY_OF_MONTH, Integer.parseInt(addtime
							.replaceAll("[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr, format.format(c.getTime()));
				} else if (addtime.endsWith("h") || addtime.endsWith("H")) {
					c.add(Calendar.HOUR, Integer.parseInt(addtime.replaceAll(
							"[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr, format.format(c.getTime()));
				} else if (addtime.endsWith("m") || addtime.endsWith("M")) {
					c.add(Calendar.MINUTE, Integer.parseInt(addtime.replaceAll(
							"[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr, format.format(c.getTime()));
				} else if (addtime.endsWith("s") || addtime.endsWith("S")) {
					c.add(Calendar.SECOND, Integer.parseInt(addtime.replaceAll(
							"[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr, format.format(c.getTime()));
				}
			} else {
				data = data.replaceFirst("time", dateString);
			}
		}
		Pattern pattern = Pattern.compile("<t[0-9]+>([\\+-]\\d+[DdHhMmSs])?");
		Matcher matcher = pattern.matcher(data);
		Calendar calender2 = Calendar.getInstance();
		while (matcher.find()) {
			String tmpstr = matcher.group();
			if (tmpstr.contains("+") || tmpstr.contains("-")) {
				String replacestr = tmpstr.split("[\\+-]")[0];
				String addtime = tmpstr.replaceFirst(replacestr, "")
						.replaceAll("\\+", "");
				if (tmpstr.contains("+")) {
					tmpstr = tmpstr.replaceAll("\\+", "\\\\\\+");
				}
				String sendtime = "";
				if (!timemap.containsKey(replacestr)) {
					try {
						throw new Exception("没有找到预先设置的变量" + replacestr);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				} else {
					sendtime = timemap.get(replacestr);
				}
				try {
					calender2.setTime(format.parse(sendtime));
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (addtime.endsWith("d") || addtime.endsWith("D")) {
					calender2.add(Calendar.DAY_OF_MONTH, Integer
							.parseInt(addtime.replaceAll("[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr,
							format.format(calender2.getTime()));
				} else if (addtime.endsWith("h") || addtime.endsWith("H")) {
					calender2.add(Calendar.HOUR, Integer.parseInt(addtime
							.replaceAll("[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr,
							format.format(calender2.getTime()));
				} else if (addtime.endsWith("m") || addtime.endsWith("M")) {
					calender2.add(Calendar.MINUTE, Integer.parseInt(addtime
							.replaceAll("[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr,
							format.format(calender2.getTime()));
				} else if (addtime.endsWith("s") || addtime.endsWith("S")) {
					calender2.add(Calendar.SECOND, Integer.parseInt(addtime
							.replaceAll("[DdHhMmSs]", "")));
					data = data.replaceAll(tmpstr,
							format.format(calender2.getTime()));
				}
			} else {
				if (!timemap.containsKey(tmpstr)) {
					data = data.replaceFirst(tmpstr, dateString);
					timemap.put(tmpstr, dateString);
				} else {
					data = data.replaceFirst(tmpstr, timemap.get(tmpstr));
				}
			}

			matcher = pattern.matcher(data);
		}
		Object[] o = new Object[2];
		o[0] = data;
		o[1] = c;
		return o;
	}
}